#!/bin/bash
###SHELLPACK preamble dbench-bench 65b19870

###SHELLPACK parseargBegin
###SHELLPACK parseargInstall
###SHELLPACK parseargEnd
###SHELLPACK monitor_hooks

###SHELLPACK check_install_required dbench-${VERSION}
###SHELLPACK init_complete

if [ "$DBENCH_OSYNC" = "yes" ]; then
	DBENCH_OSYNC_COMMAND=-s
fi
if [ "$DBENCH_SYNC_DIRECTORY" = "yes" ]; then
	DBENCH_SYNC_COMMAND=-S
fi
if [ "$DBENCH_FSYNC" = "yes" ]; then
	DBENCH_FSYNC_COMMAND=-F
fi

DBENCH_CLIENTS=`echo $DBENCH_CLIENTS | tr ',' ' '`

CLIENT=1
if [ "$DBENCH_MIN_CLIENTS" != "" ]; then
	CLIENT=$DBENCH_MIN_CLIENTS
fi

LOADDIR=$SHELLPACK_SOURCES/dbench-${VERSION}-installed/share/

if [ "$DBENCH_DURATION_FACTOR" != "" ]; then
	FACTOR=$((DBENCH_DURATION_FACTOR*1000))
else
	./bin/dbench --run-once --skip-cleanup -D $SHELLPACK_DATA \
		--loadfile $LOADDIR/client-warmup.txt $DBENCH_MAX_CLIENTS \
		&>/dev/null
	FACTOR=$(./bin/dbench $DBENCH_OSYNC_COMMAND $DBENCH_SYNC_COMMAND \
		$DBENCH_FSYNC_COMMAND --show-execute-time --run-once \
		-D $SHELLPACK_DATA --loadfile $LOADDIR/client-tiny.txt \
		--machine-readable -t 10000 $DBENCH_MAX_CLIENTS | \
		grep "^@E@" | cut -d '@' -f 4 | head -n 1)
	# We multiply the factor by 3 to get enough time for at least about 3
	# runs of each client
	FACTOR=$((FACTOR * 3 / DBENCH_MAX_CLIENTS))
fi

while [ $CLIENT -le $DBENCH_MAX_CLIENTS ]; do
	mmtests_activity client $CLIENT
	monitor_pre_hook $LOGDIR_RESULTS $CLIENT
	# Make sure test tree is clean before the run - dbench does not clean
	# up after itself
	rm -rf $SHELLPACK_DATA/clients &>/dev/null
	sync
	# First create directory hierarchy
	./bin/dbench --run-once --skip-cleanup -D $SHELLPACK_DATA \
		--loadfile $LOADDIR/client-warmup.txt $CLIENT &>/dev/null

	# Then run the benchmark
	echo dbench run $CLIENT
	BENCH_CMD="dbench $DBENCH_OSYNC_COMMAND $DBENCH_SYNC_COMMAND $DBENCH_FSYNC_COMMAND \
		-D $SHELLPACK_DATA --warmup 0 \
		-t $((DBENCH_DURATION_BASE + FACTOR*CLIENT/1000)) \
		--loadfile $LOADDIR/client-tiny.txt --show-execute-time \
		$CLIENT"
	log_cmd $BENCH_CMD
	./bin/$BENCH_CMD 2>&1 > $LOGDIR_RESULTS/dbench-$CLIENT.log
	monitor_post_hook $LOGDIR_RESULTS $CLIENT
	gzip $LOGDIR_RESULTS/dbench-$CLIENT.log
	if [ $CLIENT -lt $NUMCPUS ]; then
		CLIENT=$((CLIENT*2))
	else
		CLIENT=$((CLIENT*8))
	fi
done

exit $SHELLPACK_SUCCESS
